﻿using Credera.Theta.API;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Credera.Theta.Extensions;

namespace Credera.Theta.Modules.Environments.Commands
{
    [Command("ListEnvironments")]
    [Alias("le")]
    [Synopsis("Lists the currently available environments as well as which environments are loaded")]
    class ListEnvironmentsCommand : InputCommand
    {
        [Parameter(ordinalPosition:1, isRequired:false)]
        [Synopsis("Filters the list of availale environments")]
        public string Filter { get; set; }

        [Switch]
        public SwitchParameter LoadedOnly { get; set; }

        public override void Invoke(CommandInvocationContext context)
        {            
            if (EnvironmentLogic.Instance.EnvironmentsCollection.Environments.Count > 0)
            {
                List<Environments.Environment> environmentsToList = new List<Environments.Environment>();

                foreach (var env in EnvironmentLogic.Instance.EnvironmentsCollection.Environments)
                {
                    bool isLoaded = EnvironmentLogic.Instance.LoadedEnvironments.Contains(env);
                    bool add = true;
                    if (this.LoadedOnly.IsPresent && !isLoaded)
                        add = false;

                    if (add)
                        environmentsToList.Add(env);

                }

                if (!string.IsNullOrWhiteSpace(this.Filter))
                    environmentsToList = environmentsToList.Where(e => e.Name.IndexOf(this.Filter, StringComparison.OrdinalIgnoreCase) > -1).ToList();

                base.Out.Object.Write(TableRecords.CreateEnvironmentRecordList(environmentsToList.ToArray()));

            }
            else
            {
                base.Out.Object.Write(TableRecords.CreateEnvironmentRecordList());
            }



        }
    }
}
